# -*- coding: UTF-8 -*-

import requests

from operator import itemgetter

url='https://hacker-news.firebaseio.com/v0/topstories.json'
r=requests.get(url)
print('code:',r.status_code)

# 处理每篇文章信息

submission_ids=r.json()
submission_dicts=[]

for submisson_id in submission_ids[:5]:
	# 对于每篇文章都调用一个api
	url=('https://hacker-news.firebaseio.com/v0/item/'+str(submisson_id)+'.json')
	submission_r=requests.get(url)
	print('code:',submission_r.status_code)

	response_dict=submission_r.json()

	submission_dict={
		'title':response_dict['title'],
		'link':'http://news.ycombinator.com/item?id='+str(submisson_id),
		'comments':response_dict.get('descendants',0)

	}

	print(submission_dict['comments'])
	submission_dicts.append(submission_dict)


submission_dicts=sorted(submission_dicts,key=itemgetter('comments'),reverse=True)

for submission_dict in submission_dicts:
	print('title:',submission_dict['title'])
	print('Discussion link:',submission_dict['link'])
	print('Comments:',submission_dict['comments'])